package xyz.jiayin.iceorangesip;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.csipsimple.VoipUtil;
import com.csipsimple.api.ISipService;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipProfile;
import com.csipsimple.service.SipService;
import com.csipsimple.utils.AccountListUtils;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesProviderWrapper;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private Button startService, stopService;
    private EditText username, password;
    private TextView status;
    private ISipService sipService;

    PreferencesProviderWrapper prefsWrapper;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sipService = ISipService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            sipService = null;
        }
    };

    private Timer timer = new Timer();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            AccountListUtils.AccountStatusDisplay display = (AccountListUtils.AccountStatusDisplay) msg.obj;
            status.setText(display.statusLabel);
            status.setTextColor(display.statusColor);
        }
    };


    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    private static String strFilePath = "logs.txt";

    public  void WriteTxtFiles(String strcontent)
    {
        //每次写入时，都换行写
        String strContent= DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM,Locale.CHINA).format(new Date()) + "\t" + strcontent+"\n";
        String filePath;
        //String filePath = getApplicationContext().getFilesDir().getAbsolutePath() + "/logs.txt";
        if(Build.VERSION.SDK_INT >= 19) {
            filePath = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/logs.txt";
        }else{
            filePath = Environment.getDownloadCacheDirectory().getAbsolutePath() + "/logs.txt";
        }
        try {
            String strFile;
            File file = new File(filePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                if (file.getParentFile() != null && !file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
            Toast.makeText(this, "sucess:" + filePath, Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File.");
            Toast.makeText(this, "fail"+ e.toString() + ":" + filePath, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         prefsWrapper = new PreferencesProviderWrapper(this);

        if(Build.VERSION.SDK_INT >= 19) {
            strFilePath = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/logs.txt";
        }else{
            strFilePath = getApplicationContext().getFilesDir() + "/logs.txt";
        }

        WriteTxtFiles("Main activity started");

        setContentView(R.layout.activity_main);

        PackageManager pkgManager= getPackageManager();

        boolean audioSatePermission =

                pkgManager.checkPermission(Manifest.permission.RECORD_AUDIO, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if(Build.VERSION.SDK_INT>=23&&!audioSatePermission) {
            ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.RECORD_AUDIO},

             0);
        }

        startService = (Button)findViewById(R.id.start_service);
        stopService = (Button)findViewById(R.id.stop_service);
        status = (TextView)findViewById(R.id.reg_status);
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);

//        String u = "o96dJwNmUTuaCvw89gCxQgCNpllg";
//        String p = "4ptymO";
        String u = "o96dJwCeCz9rwAyWjPd7JyU3mqks";
        String p = "GVIn7";
        VoipUtil.startRegisterService(this, u, p, 300);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                AccountListUtils.AccountStatusDisplay display = AccountListUtils.getAccountDisplay(getApplicationContext(), 1);
                Message msg = new Message();
                msg.obj = display;
                handler.sendMessage(msg);
            }
        },1,1000);

        startService.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                //serviceIntent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, new ComponentName(MainActivity.this, MainActivity.class));
                hideInput();
                String u = username.getText().toString();
                String p = password.getText().toString();
                if(u.isEmpty() || p.isEmpty()) {
                    Toast.makeText(MainActivity.this, "用户名或密码不能为空!", Toast.LENGTH_LONG).show();
                    username.requestFocus();
                }else{
                    username.clearFocus();
                    password.clearFocus();
                    startService.clearFocus();
                    VoipUtil.startRegisterService(MainActivity.this, u, p, 300);
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            String status = VoipUtil.getRegisterStatus(MainActivity.this);
                            AccountListUtils.AccountStatusDisplay display = AccountListUtils.getAccountDisplay(getApplicationContext(), 1);
                            Message msg = new Message();
                            msg.obj = display;
                            handler.sendMessage(msg);
                        }
                    },1,1000);
                }
            }
        });

        stopService.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v){
                VoipUtil.stopRegisterService();
            }
        });
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }
}
